import { BASE_URL, DOMAIN_NAME } from "../../api/config";
import { get } from "../../api/request";

Component({
  data: {
    show: false,
    userInfo: {
      avatarUrl: '',
      nickName: ''
    },
    isSubmitting: false
  },

  lifetimes: {
    attached: function () {
      console.log('登录组件已加载');
      // 注册登录组件到全局认证管理器
      const app = getApp();
      if (app && app.globalData && app.globalData.authManager) {
        console.log('正在注册登录组件到认证管理器');
        app.globalData.authManager.setLoginPopup(this);
      } else {
        console.error('无法获取全局认证管理器');
      }
    }
  },

  methods: {
    showPopup() {
      console.log('显示登录弹窗');
      this.setData({ show: true });
    },

    onClose() {
      this.setData({ show: false });
    },

    chooseAvatar(e) {
      const { avatarUrl } = e.detail;
      this.setData({
        'userInfo.avatarUrl': avatarUrl
      });
    },

    onInputNickname(e) {
      const nickName = e.detail.value;
      this.setData({
        'userInfo.nickName': nickName
      });
    },

    handleLogin() {
      const { avatarUrl, nickName } = this.data.userInfo;
      if (!avatarUrl || !nickName) {
        wx.showToast({
          title: '请完善信息',
          icon: 'none'
        });
        return;
      }

      // 避免重复提交
      if (this.data.isSubmitting) {
        return;
      }
      this.setData({ isSubmitting: true });
      // 获取Token (假设你已经在某处存储了token)
      const token = wx.getStorageSync('token') || '';
      // 调用上传接口
      wx.uploadFile({
        url: BASE_URL + '/user/authorization', // 假设你在app.js中定义了baseUrl
        filePath: avatarUrl,
        name: 'avatar_img',
        header: {
          'Authorization': `Bearer ${token}`
        },
        formData: {
          'nickname': nickName
        },
        success: (res) => {
          const response = JSON.parse(res.data);
          console.log('response', response);
          if (response.code === 200) {
            // 更新本地缓存中的 userInfo.auth 为 true
            const userInfo = wx.getStorageSync('userInfo');
            if (userInfo) {
              userInfo.auth = true;
              wx.setStorageSync('userInfo', userInfo);
            }
            wx.showToast({
              title: response.message,
              icon: 'success'
            });
            get('/user/my').then(res => {
              if (res.code === 200) {
                const { data } = res;
                console.log('data', data);
                // wx.setStorageSync('userInfo', data)
              }
            })
            setTimeout(() => {
              this.setData({
                show: false
              })
            }, 800)
          }

        },
        fail: (err) => {
          console.error('上传失败', err);
          wx.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
          });
        },
        complete: () => {
          this.setData({ isSubmitting: false });
        }
      });
    }
  }
})